package com.bsj.power.system.web;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bsj.power.common.annotation.Log;
import com.bsj.power.common.config.exception.ApiException;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.global.TokenUser;
import com.bsj.power.common.constant.SysLogTitleConst;
import com.bsj.power.common.def.dto.PageDTO;
import com.bsj.power.common.def.dto.user.UserAddDTO;
import com.bsj.power.common.def.dto.user.UserModifyPasswordDTO;
import com.bsj.power.common.def.entity.user.User;
import com.bsj.power.common.def.enums.BusinessType;
import com.bsj.power.common.def.vo.pls.httpVo.HttpLoginPersonVO;
import com.bsj.power.common.def.vo.web.system.user.UserVO;
import com.bsj.power.common.mapper.SystemOpLogMapper;
import com.bsj.power.common.mapper.UserMapper;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.common.util.IpUtils;
import com.bsj.power.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description 系统用户管理
 * @date 2024/4/22
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
//@SaCheckPermission("/master/system/user")
public class SystemUserController {

    @Autowired
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private SystemOpLogMapper systemOpLogMapper;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @SaIgnore
    @GetMapping(value = "/doLogin")
    @Log(title = SysLogTitleConst.USER_MODULE, desc = "用户登录", businessType = BusinessType.LOGIN)
    public JsonResult<TokenUser> doLogin(String username, String password, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ApiException(JsonResultEnum.NOT_USER_AND_PASSWORD_ISNULL);
        }
        return userService.login(username, password, request);
    }

    @GetMapping(value = "/test")
    public JsonResult test() {
        String dateToStr = DateUtils.dateToStr(new Date());
        HttpLoginPersonVO httpLoginPersonVO = new HttpLoginPersonVO("1", "muyanga", "muyang", "muyanga", "1", "沐阳", "男", "xxxxxx@163.com", "13728374659", "13728374659", dateToStr, dateToStr);
        User user = httpLoginPersonVO.change();
        user.setParentId(userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getParentId, -1)).getUserId());
        userMapper.batchInsert(List.of(user));
        return JsonResult.success();
    }

    /**
     * 用户登出
     *
     * @return
     */
    @GetMapping(value = "/doLogout")
    @Log(title = SysLogTitleConst.USER_MODULE, desc = "用户登出", businessType = BusinessType.LOG_OUT)
    public JsonResult doLogout(Integer userId) {
//        try {
//            TokenUser tokenInfo = StpLoginUserUtil.getTokenUser();
//            if (tokenInfo != null) {
//                SystemOpLog systemOpLog = new SystemOpLog();
//                int type = SystemOpTypeEnum.LOGOUT.getOpType();
//                systemOpLog.setOpUserId(tokenInfo.getUserId());
//                systemOpLog.setOpUserName(tokenInfo.getUserName());
//                systemOpLog.setName(VideoOpTypeEnum.getByValue(type));
//                systemOpLog.setOpType(type);
//                Date date = new Date();
//                systemOpLog.setOpTime(date);
//                systemOpLog.setCreateTime(date);
//                UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
//                systemOpLog.setIp(request.getRemoteAddr().equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : request.getRemoteAddr());
//                systemOpLog.setBrowser(userAgent.getBrowser().toString());
//                systemOpLog.setOs(userAgent.getOs().toString());
//                systemOpLogMapper.insert(systemOpLog);
//            }
//        } catch (Exception e) {
//            log.error("记录日志失败：{}", ExceptionUtil.getStackStr(e));
//        }

        StpUtil.logoutByTokenValue(StpUtil.getTokenValue());

        return JsonResult.success();
    }

    /**
     * 修改用户密码
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/modifyPassWord")
    public JsonResult<Integer> modifyPassWord(HttpServletRequest request, @Valid @RequestBody UserModifyPasswordDTO dto) {
        return JsonResult.success(userService.modifyPassWord(dto, IpUtils.getIp(request)));
    }

    /**
     * 重置密码
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/resetPassword")
    public JsonResult<String> resetPassword(HttpServletRequest request, Long userId) {
        if (userId == null) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR);
        }
        return JsonResult.success(userService.resetPassword(userId, IpUtils.getIp(request)));
    }

    /**
     * 新增和修改用户
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/addAndUpdateUser")
    public JsonResult<Long> addAndUpdateUser(HttpServletRequest request, @Valid @RequestBody UserAddDTO dto) {
        Long userId = dto.getUserId();
        //新增
        if (userId == null) {
            if (dto.getPassword() == null || dto.getUserName() == null
                    || dto.getPhone() == null || dto.getRoleId() == null) {
                //参数必填
                throw new ApiException(JsonResultEnum.PARAM_ERROR);
            }
        }
        return JsonResult.success(userService.addAndUpdateUser(dto, IpUtils.getIp(request)));
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/deleteUser")
    public JsonResult<Integer> deleteUser(HttpServletRequest request, Long userId) {
        if (userId == null) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR);
        }
        return JsonResult.success(userService.deleteUser(userId, IpUtils.getIp(request)));
    }

    /**
     * 分页获取用户列表
     *
     * @param dto
     * @return
     */
    @GetMapping("/doPageUserList")
    public JsonResult<List<UserVO>> doPageUserList(@Valid PageDTO dto, String userName, String loginId, Integer groupId) {
        return userService.pageUserList(dto, userName, loginId, groupId);
    }

    /**
     * 设置访问权限
     *
     * @param userId
     * @param isAccess 是否允许访问 1是 2否
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/9/2 15:41
     */
    @GetMapping(value = "/setAccessAuth")
    public JsonResult setAccessAuth(HttpServletRequest request, Long userId, Integer isAccess) {
        if (userId == null || isAccess == null) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR);
        }
        return userService.setAccessAuth(userId, isAccess, IpUtils.getIp(request));
    }

    /**
     * 获取登录用户信息
     *
     * @param sessionId
     * @return com.bsj.power.common.config.global.JsonResult<com.bsj.power.common.config.global.TokenUser>
     * @author ljx
     * @time 2024/9/2 16:45
     */
    @SaIgnore
    @GetMapping(value = "/getLoginInfo")
    public JsonResult<TokenUser> getLoginInfo(String sessionId) {
        if (StringUtils.isBlank(sessionId)) {
            return JsonResult.fail(JsonResultEnum.PARAM_ERROR);
        }
        TokenUser tokenUser = userService.getLoginInfo(sessionId);
        if (tokenUser == null) {
            return JsonResult.fail();
        } else {
            return JsonResult.success(tokenUser);
        }
    }

    /**
     * 取消锁定
     *
     * @param userId
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/9/27 15:09
     */
    @GetMapping(value = "/cancelLock/{userId}")
    public JsonResult cancelLock(HttpServletRequest request, @PathVariable("userId") Integer userId) {
        return userService.cancelLock(userId, IpUtils.getIp(request));
    }

}
